<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Stroop extends CI_Controller
{
	function Stroop()
	{
		parent::__construct();
        $this->load->model('common/common_model');
        $this->load->model('stroop/stroop_model');
        
        $this->load->library('Myinfo');
	}
	
	public function index()
	{
        if(!$this->session->userdata('username'))
        {
            redirect(site_url('login'));
            die();
        }	   
        $data = array();
        $userid = $this->session->userdata('uid');
        $user_oasis_orderid = $this->session->userdata('oasis_orderid');
        $c = (int)$this->input->get('c');
        if($c!=$user_oasis_orderid)
        {
            $oasisId = $this->common_model->ww_get_map_user_info($userid, $c);
            if($oasisId)
            {
                $this->session->set_userdata('oasis_orderid', $oasisId['oasis_orderid']);
            }
            else
            {
                redirect(site_url('home'));
                die();
            }
            $user_oasis_orderid = $oasisId['oasis_orderid'];
        }
        $data = $this->myinfo->loadUserinfo($userid, $user_oasis_orderid);
        /**/
        
        $send = $this->stroop_model->ww_get_all_send_stroop_by_user($userid, $user_oasis_orderid, 0);
        $data['send_troop'] = false;
        if($send)
        {
            $data['send_troop'] = true;
            $data['send'] = $send;
        }
        /*
        * End load
        */
		// header
		
		// content
		$this->load->view('stroop/stroop_view', $data);
		
		// footer
	}
    
    function review_coor_send()
    {
        if(!$this->session->userdata('username'))
        {
            redirect(site_url('login'));
            die();
        }
        $data = array();
        $this->load->model('map/map_model');
        $userid = $this->session->userdata('uid');
        $user_oasis_orderid = $this->session->userdata('oasis_orderid');
        $rx = (int)$this->input->get('rootx');
        $ry = (int)$this->input->get('rooty');
        $info = $this->market_model->ww_get_field_around_coor($userid, $user_oasis_orderid, $rx, $ry);
        if($info)
        {
            $data['info'] = $info;
            $t_arrxy =  array(
                                'x' => $rx,
                                'y' => $ry
                            );
            $loc_user = $this->map_model->ww_get_map_user_info($userid, $user_oasis_orderid);
            $u_arrxy =  array(
                                'x' => $loc_user['x'],
                                'y' => $loc_user['y']
                            );
            $distanceTime = $this->mycommon->distanceTime($u_arrxy, $t_arrxy, 5, 400);
    
            $data['distance'] = gmdate('H:i:s', $distanceTime);
            $this->load->view('market/lst_filed_view', $data);
        }
        else
        {
            echo 'NULL';
        }
    }
    
    function send()
    {
        if(!$this->session->userdata('username'))
        {
            redirect(site_url('login'));
            die();
        }
        
        $userid = $this->session->userdata('uid');
        $user_oasis_orderid = $coor = (int)$this->input->get('coor');
        $oasisId = $this->map_model->ww_get_map_user_info($userid, $coor);
        if(!$oasisId)
        {
            echo 'error';
            die();
        }
        
        $rx = intval($this->input->get('rootx', true));
        $ry = intval($this->input->get('rooty', true));
        $xx = intval($this->input->get('xx'));
        $yy = intval($this->input->get('yy'));
        $info = $this->market_model->ww_get_info_field_coor($rx, $ry, $xx, $yy);
        $mapuser = $this->map_model->ww_get_map_user_info($userid, $user_oasis_orderid);
        /*to*/
        $to_userid = $info['occupied'];
        $to_oasis_orderid = $info['oasis_orderid'];
        /*type*/
        $type = 0; // gửi thông thường(o to, tau thuy may bay).
        
        $distanceTime = $this->mycommon->distanceTime(array('x'=>$mapuser['x'], 'y'=>$mapuser['y']),array('x'=>$rx, 'y'=>$ry), 5, 400);
        $this->update_all_res_user($userid, $user_oasis_orderid);
        $res = $this->common_model->ww_get_res_user_info_by_field($userid, $user_oasis_orderid);
        
        $sfood = (int)$this->input->get('sfood');
        $swood = (int)$this->input->get('swood');
        $smetal = (int)$this->input->get('smetal');
        $spetro = (int)$this->input->get('spetro');
        
        $sfood = $sfood > $res['food'] ? $res['food'] : $sfood;
        $swood = $swood > $res['wood'] ? $res['wood'] : $swood;
        $smetal = $smetal > $res['metal'] ? $res['metal'] : $smetal;
        $spetro = $spetro > $res['petroleum'] ? $res['petroleum'] : $spetro;
        
        if($sfood>0||$swood>0||$smetal>0||$spetro>0)
        {
            $this->market_model->ww_send_resoure($userid, $user_oasis_orderid, $to_userid, $to_oasis_orderid, 
        $sfood, $swood, $smetal, $spetro, $distanceTime, $type);   
        }
        die();
    }
    
    function chk_send_troop_for_user($uid, $oasis_orderid)
    {
        /*
        * list all send troop has complete by user
        */
        $info = $this->stroop_model->ww_get_all_send_stroop_by_user($uid, $oasis_orderid, 1);
        foreach ($info as $if)
        {
            /*
            *  update from user -> to other user
            */
            $this->common_model->ww_update_wave_by_user($if['id'], $if['from_uid'], $if['from_oasis_orderid'], $if['to_uid'], $if['tooasis_orderid']);
        }
    }
    
    /*
    * -------------------------------------------------------------------------------------
    * Load for upgrade infomation user
    */
    /*
    * get resource from source
    */
	function run_time_res($uid)
	{
		$food = 60000/($this->_food/60);
		$wood = 60000/($this->_wood/60);
		$metal = 60000/($this->_metal/60);
		$petroleum = 60000/($this->_petroleum/60);
		
		$result = array($food, $wood, $metal, $petroleum);
		return $result;
	}
    /*
    * update resource to db
    */
    function update_all_res_user($uid, $oasis_orderid)
	{
		$data = array();
		$food = $this->_food;
		$wood = $this->_wood;
		$metal = $this->_metal;
		$petroleum = $this->_petroleum;
		$time = time();
		$res = $this->common_model->ww_get_res_user_info_by_field($uid);
		
		$lastupdate = $res['lastupdate'];
		
		$valFloat = (((($time - $lastupdate)/60)/60)/2);
		$food = floor($valFloat*$food);
		$wood = floor($valFloat*$wood);
		$metal = floor($valFloat*$metal);
		$petroleum = floor($valFloat*$petroleum);
        
        $food = $res['maxstore'] < $res['food'] + $food ? $res['maxstore'] - $res['food'] : $food;
        $wood = $res['maxstore'] < $res['wood'] + $wood ? $res['maxstore'] - $res['wood'] : $wood;
        $metal = $res['maxstore'] < $res['metal'] + $metal ? $res['maxstore'] - $res['metal'] : $metal;
        $petroleum = $res['maxstore'] < $res['petroleum'] + $petroleum ? $res['maxstore'] - $res['petroleum'] : $petroleum;
        
		if($food >= 1 || $wood >= 1 || $metal >= 1 || $petroleum >= 1)
		{
            $update_res_by_hour = $this->common_model->ww_update_res_by_hour($uid, $oasis_orderid=0, $food, $wood, $metal, $petroleum, $time);
		}
	}
    
    /*
    * update building for user
    */
    function upgrade_build_for_user($uid, $land)
    {
        $upgrade = $this->common_model->ww_get_user_info_build($uid, $land);
        /*
        check 
        */
        $arr_v1 = array();// build complete.
        $arr_v2 = array();// build close complete.
        $build_v2 = array();
        $chk_complete = false;
        foreach($upgrade as $lst)
        {
            $time_of_upgrade = $lst['timestamp'] + $lst['eachtime'];
            $now = time();
            $pastTime = $now - $time_of_upgrade;
            if($pastTime >= 0)
            {
                // complete
                $arr_v1['id'][] = $lst['id'];
                $arr_v1['buildid'][] = $lst['buildid'];
                $chk_complete = true;
            }
            else
            {
                // close complete
                $arr_v2['id'] = $lst['id'];
                $arr_v2['rtime'] = $lst['timestamp'] + $lst['eachtime'] - $now;
                $build_v2[] = $arr_v2;
            }
        }
       
        $strSuccess = '';
		if($chk_complete)
		{
			$lstid = join(",", $arr_v1['id']);
            $i=0;
			foreach($arr_v1['buildid'] as $lstBuild)
			{
				$strSuccess .= 'b'.$lstBuild.'=b'.$lstBuild.'+1,';
				$i++;
			}
            $strSuccess = substr($strSuccess, 0, -1);
            
			$this->common_model->ww_update_build_by_user($uid, $land, $strSuccess, $lstid);
		}
        return $build_v2;
    }
    
	public function update_all_info_user($uid)
	{
	   if(!$this->session->userdata('username'))
       {
            redirect(site_url('login'));
            die();
       }
		/*
		* update_all_info_user
		*/
		$info_train = $this->common_model->ww_get_train_user_info($uid, 0);
		
		$arrUnit = array();
		$arrVal = array();
		$strSuccess = '';
		$chkExistsCompleteTrain = false;
		foreach($info_train as $info)
		{
			// dat thoi gian tre khoang 5s.
			$timestamp = $info['timestamp'] + $info['eachtime'] + 5;
			$timenow = time();
			
			if($timenow > $timestamp)
			{
				/*
				* check id nhung traning da dc hoan thanh.
				*/
				$arrIDSuccess[] = $info['id'];
				if(!in_array('u'.$info['unit'], $arrUnit))
				{
					$arrUnit[] = 'u'.$info['unit'];
					$arrVal[] = $info['lquantity'] - $info['quantity'];
				}
				else
				{
					$valKey = array_search('u'.$info['unit'], $arrUnit);
					$arrVal[$valKey] = $arrVal[$valKey] + $info['lquantity'] - $info['quantity'];
				}
				$chkExistsCompleteTrain = true;
			}
			else
			{
				/*
				* check id nhung traning chua hoan thanh, chay thoi gian.
				*/
				
				// thoi gian hoan thanh tren db.
				$chkTime_v1 = $info['timestamp'] + $info['eachtime'];
				// thoi gian hien tai + thoi gian chuan hoan thanh khong tinh thoi gian traning truoc.
				$chkTime_v2 = $timenow + $info['fixtime']*$info['lquantity'];
				
				// thoi gian hoan thanh - thoi gian can ban de lay thoi gian du.
				$chkTime_v3 = $info['eachtime'] - $info['fixtime']*$info['lquantity'];
				
				
				// neu thoi gian 2 > thoi gian 1-> thoi gian hien tai da chuan bi hoan thanh
				//, kiem tra traning do'.
				if($chkTime_v2 > $chkTime_v1)
				{
					// gia tri $quantity la so nguyen to cua so luong da hoan thanh.
					$decimal = ($timenow - ($info['timestamp']+$chkTime_v3))/$info['fixtime'];
					$quantity = floor($decimal);
					$quantity = $quantity > $info['lquantity'] ? $info['lquantity'] : $quantity;
					
					if($decimal >= 1 && $quantity>=1 && $quantity > $info['quantity'])
					{
						$quantity = $quantity - $info['quantity'];
                        $this->common_model->ww_update_quantity_for_time($info['id'], $uid, $quantity);
					}
				}
			}
			// end if
		}
		/*
		* thao tac hoan thanh len db.
		*/
        
		if($chkExistsCompleteTrain)
		{
			$arrStr = array();
			$lstid = join(",", $arrIDSuccess);
			$i = 0;
			foreach($arrUnit as $typeUnit)
			{
				$strSuccess .= $typeUnit.'='.$typeUnit.'+'.$arrVal[$i].',';
				$i++;
			}
			$strSuccess = substr($strSuccess, 0, -1);
			$this->common_model->ww_update_quantity_military($uid, $strSuccess, $lstid);
		}
		// end for
	}
    /*
    * ------------------------------------------------------------------------------
    * End load
    */
}